package com.wx.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.wx.commons.WxMenuTreeUtil;
import com.wx.core.vo.MenuTree;
import com.wx.entity.SysWxuser;
import com.wx.entity.WxMenu;
import com.wx.entity.WxMenuExample;
import com.wx.service.SysWxTokenService;
import com.wx.service.SysWxuserService;
import com.wx.service.WxMenuService;
import com.wx.util.JsonResult;
import com.wx.util.JsonUtil;
import com.wx.validate.RegexUtils;
import com.wx.vo.WxRootMenu;
import com.zyht.common.AbsManageBaseController;
import com.zyht.website.entity.SysUser;

@Controller
@RequestMapping("admin/wxmenu")
public class WxMenuController extends AbsManageBaseController {

	@Resource
	private WxMenuService wxMenuService;
	@Value("#{propertiesReader[session_wx_key]}")
	private String session_wx_key;
	@Resource
	private SysWxuserService sysWxuserService;

	@Resource
	private SysWxTokenService sysWxTokenService;

	private static final Logger logger = LoggerFactory.getLogger(WxMenuController.class);

	@RequestMapping(value = "/index",method = RequestMethod.GET)
	public String index(@RequestParam(value = "menu_id",required = false) final String menu_id,HttpSession session,HttpServletRequest request,
		HttpServletResponse response){

		SysWxuser sysWxuser = (SysWxuser) session.getAttribute(session_wx_key);
		String wxid = sysWxuser.getWxid();
		WxMenuExample exp = new WxMenuExample();
		exp.createCriteria().andWxidEqualTo(wxid);
		List<WxMenu> list = wxMenuService.selectByExample(exp);
		List<WxRootMenu> rootList = new ArrayList<WxRootMenu>();
		WxMenu menu = new WxMenu();
		for(WxMenu wxMenu:list){
			if(RegexUtils.isNumber(menu_id) && wxMenu.getId().intValue() == Integer.valueOf(menu_id))
				menu = wxMenu;
			if(wxMenu.getPid() == 0){// 构建父节点对象
				WxRootMenu rootMenu = new WxRootMenu();
				BeanUtils.copyProperties(wxMenu,rootMenu);
				rootMenu.setChildList(new WxMenuTreeUtil().getChild(wxMenu.getId(),list));
				rootList.add(rootMenu);
			}
		}
		new WxMenuTreeUtil().sortRootList(rootList);
		// 当前菜单
		request.setAttribute("now_menu",menu);
		request.setAttribute("menu_id",menu_id);
		// 用户所有菜单集合
		request.setAttribute("rootList",rootList);
		// 设置三个子菜单
		request.setAttribute("child1_list",rootList.size() > 1 ? rootList.get(0).getChildList() : null);
		request.setAttribute("child2_list",rootList.size() > 2 ? rootList.get(1).getChildList() : null);
		request.setAttribute("child3_list",rootList.size() >= 3 ? rootList.get(2).getChildList() : null);
		return "/basic/menus/index";
	}

	@RequestMapping(value = "/getByid",method = RequestMethod.GET,produces = "application/json; charset=utf-8")
	public @ResponseBody String getByid(@RequestParam(value = "id",required = true) final String id){

		WxMenu wxMenu = wxMenuService.selectByPrimaryKey(Integer.valueOf(id));
		return JsonUtil.Object2Json(JsonResult.objectJson(wxMenu));
	}

	@RequestMapping(value = "/updateByid",method = RequestMethod.GET)
	public String updateByid(HttpServletRequest request,HttpServletResponse response,@RequestParam(value = "menu_id",required = true) final String menu_id,
		@RequestParam(value = "pid",required = true) final String pid,@RequestParam(value = "title",required = true) final String title,
		@RequestParam(value = "is_show",required = true) final String is_show,@RequestParam(value = "sort",required = true) final String sort,
		@RequestParam(value = "menu_type",required = true) final String menu_type,@RequestParam(value = "keyword",required = false) final String keyword,
		@RequestParam(value = "url",required = false) final String url,@RequestParam(value = "key_id",required = false) final String key_id,
		@RequestParam(value = "key_type",required = false) final String key_type){

		String refererUrl = "http://" + request.getServerName();
		if(request.getServerPort() > 0 && request.getServerPort() != 80){
			refererUrl = refererUrl + ":" + request.getServerPort();
		}
		refererUrl = refererUrl + request.getContextPath(); // 项目名称
		String wxid = getWxId(request);
		if(url.indexOf("http://") == -1 && url.indexOf("https://") == -1){
			refererUrl = refererUrl + url + "?wxid=" + wxid;
		} else{
			refererUrl = url;
		}
		System.out.println("ServerName=" + request.getServerName() + "&ContextPath=" + request.getContextPath());
		WxMenu wxMenu = wxMenuService.selectByPrimaryKey(Integer.valueOf(menu_id));
		if(RegexUtils.isNumber(pid))
			wxMenu.setPid(Integer.valueOf(pid));
		if(!RegexUtils.isNull(title))
			wxMenu.setmName(title);
		wxMenu.setIsShow(Integer.valueOf(is_show));
		if(RegexUtils.isNumber(sort))
			wxMenu.setmOrder(Integer.valueOf(sort));
		if(RegexUtils.isNumber(key_id))
			wxMenu.setKeyId(Integer.valueOf(key_id));
		if(RegexUtils.isNumber(key_type))
			wxMenu.setKeyType(Integer.valueOf(key_type));
		wxMenu.setType(Integer.valueOf(menu_type));
		wxMenu.setmKeyword(keyword);
		wxMenu.setmHref(refererUrl);

		wxMenuService.updateByPrimaryKey(wxMenu);

		return "redirect:index";
	}

	@RequestMapping(value = "/add",method = RequestMethod.GET)
	public String add(HttpServletRequest request,HttpServletResponse response,HttpSession session,
		@RequestParam(value = "pid",required = true) final String pid,@RequestParam(value = "title",required = true) final String title,
		@RequestParam(value = "is_show",required = true) final String is_show,@RequestParam(value = "sort",required = true) final String sort,
		@RequestParam(value = "menu_type",required = true) final String menu_type,@RequestParam(value = "keyword",required = false) final String keyword,
		@RequestParam(value = "url",required = false) final String url,@RequestParam(value = "key_id",required = false) final String key_id,
		@RequestParam(value = "key_type",required = false) final String key_type){

		String refererUrl = "http://" + request.getServerName();

		if(request.getServerPort() > 0 && request.getServerPort() != 80){
			refererUrl = refererUrl + ":" + request.getServerPort();
		}
		refererUrl = refererUrl + request.getContextPath(); // 项目名称
		SysWxuser sysWxuser = (SysWxuser) session.getAttribute(session_wx_key);
		String wxid = sysWxuser.getWxid();
		if(url.indexOf("http://") == -1 && url.indexOf("https://") == -1){
			refererUrl = refererUrl + url + "?wxid=" + wxid;
		} else{
			refererUrl = url;
		}

		if(!RegexUtils.isNumber(sort)){
			logger.debug("排序格式错误");
			request.setAttribute("msg","排序格式错误");
			return "forward:index";// 根节点超过3个
		}
		// 判断根节点不能超过3个，子节点不能超过5个
		WxMenuExample exp = new WxMenuExample();
		exp.createCriteria().andWxidEqualTo(wxid);
		List<WxMenu> list = wxMenuService.selectByExample(exp);
		WxMenuTreeUtil wxMenuTree = new WxMenuTreeUtil();
		if(Integer.valueOf(pid) == 0 && wxMenuTree.getRootNum(list) >= 3){
			logger.debug("添加根节点超过3个");
			request.setAttribute("msg","添加根节点超过3个");
			return "forward:index";// 根节点超过3个
		}
		if(Integer.valueOf(pid) != 0 && wxMenuTree.getChirldNum(Integer.valueOf(pid),list) >= 5){
			logger.debug("添加子节点超过5个：");
			request.setAttribute("msg","添加子节点超过5个");
			return "forward:index";
		}
		WxMenu wxMenu = new WxMenu();
		if(RegexUtils.isNumber(pid))
			wxMenu.setPid(Integer.valueOf(pid));
		if(!RegexUtils.isNull(title))
			wxMenu.setmName(title);

		wxMenu.setIsShow(Integer.valueOf(is_show));
		wxMenu.setmOrder(Integer.valueOf(sort));
		wxMenu.setType(Integer.valueOf(menu_type));
		if(RegexUtils.isNumber(key_id))
			wxMenu.setKeyId(Integer.valueOf(key_id));
		if(RegexUtils.isNumber(key_type))
			wxMenu.setKeyType(Integer.valueOf(key_type));
		wxMenu.setmKeyword(keyword);
		wxMenu.setmHref(refererUrl);
		wxMenu.setCreateTime(new Date());

		SysUser session_user = getSessionUser(request);
		wxMenu.setUid(session_user.getId());
		wxMenu.setWxid(wxid);
		wxMenuService.insert(wxMenu);
		return "redirect:index";
		// return "forward:/index";
	}

	@RequestMapping(value = "/delete",method = RequestMethod.GET)
	public String delete(@RequestParam(value = "id",required = true) final String id,HttpServletRequest request){

		if(!RegexUtils.isNumber(id)){
			logger.debug("删除节点参数错误");
			request.setAttribute("msg","删除节点参数错误");
			return "forward:index";
		}
		// 查询下面是否有子节点，存在则不允许删除
		WxMenuExample exp = new WxMenuExample();
		exp.createCriteria().andPidEqualTo(Integer.valueOf(id));
		List<WxMenu> list = wxMenuService.selectByExample(exp);
		if(list.size() > 0){
			logger.debug("请先删除子节点");
			request.setAttribute("msg","请先删除子节点");
			return "forward:index";
		}
		wxMenuService.deleteByPrimaryKey(Integer.valueOf(id));
		request.setAttribute("msg","删除成功");
		return "forward:index";
	}

	@RequestMapping(value = "/create",method = RequestMethod.GET)
	public String create(Model model,HttpServletRequest request){

		String wxid = getWxId(request);
		SysWxuser sysWxuser = sysWxuserService.selectByWxid(wxid);
		if(sysWxuser == null){
			request.setAttribute("msg","微信ID错误");
			return "forward:index";
		}
		// 查询 显示 的数据
		WxMenuExample exp = new WxMenuExample();
		exp.createCriteria().andWxidEqualTo(wxid);
		List<WxMenu> list = wxMenuService.selectByExample(exp);
		List<MenuTree> relist = new WxMenuTreeUtil().createWxMenu(list);
		HashMap<String, List<MenuTree>> map = new HashMap<String, List<MenuTree>>();
		map.put("button",relist);
		Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
		String wxjson = gson.toJson(map);
		if(logger.isDebugEnabled()){
			logger.debug("生成菜单JSON为：\n" + wxjson);
			logger.debug("公众号信息如下：\n" + JSON.toJSONString(sysWxuser));
		}

		wxMenuService.createWxMenus(sysWxuser.getId(),sysWxuser.getWxid(),sysWxuser.getAppid(),sysWxuser.getAppsecretd(),wxjson);

		model.addAttribute("msg","生成菜单成功");
		model.addAttribute("redirect","admin/wxmenu/index");
		return "message";
	}

	@RequestMapping(value = "/deleteMenu",method = RequestMethod.GET)
	public String deleteMenu(Model model,HttpServletRequest request){

		String wxid = getWxId(request);
		SysWxuser sysWxuser = sysWxuserService.selectByWxid(wxid);
		if(sysWxuser == null){
			request.setAttribute("msg","微信ID错误");
			return "forward:index";
		}
		String accessToken = sysWxTokenService.getAccessToken(sysWxuser.getWxid(),sysWxuser.getAppid(),sysWxuser.getAppsecretd());
		JSONObject reqJson = wxMenuService.deleteWxMenus(accessToken);
		if(reqJson.getString("errmsg").equals("ok")){
			model.addAttribute("msg","删除自定义菜单成功");
		} else{
			model.addAttribute("msg","删除自定义菜单失败");
		}
		model.addAttribute("redirect","wxmenu/index");
		return "message";
	}

}
